package com.dman.multi.algo;

import java.io.IOException;
import java.util.List;

import com.dman.multi.core.Section;

public class FixedSectionAlgo implements SectionAlgo {

	public static final int MIN_THREADS = 5;
	public static final long MAX_FILE_SIZE = 500 * 1024 * 1024;
	public static final long THR_INC_SIZE = 200 * 1024 * 1024;

	@Override
	public int createSection(List<Section> secList)	throws SectionCreationException {
		
		// get the length of section
		Section sec = secList.get(0);
		long size = sec.getSize();
		int numThreads = MIN_THREADS;
		long threadInc = (size - MAX_FILE_SIZE) / THR_INC_SIZE;
		int len = secList.size();
		
		// compute thread increment
		if(threadInc > 0)
			numThreads += threadInc + 1;
		
		if(secList.size() >= numThreads)
			throw new SectionCreationException();
		
		try {
			Section newSec = new Section(sec.getStrUrl(), size / numThreads * len);
			secList.add(newSec);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return len;
	}

}
